package fr.norsys.mapper.console.web;

import java.util.Iterator;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import fr.norsys.mapper.console.model.Application;
import fr.norsys.mapper.console.model.Attribute;
import fr.norsys.mapper.console.model.ConsoleCst;
import fr.norsys.mapper.console.model.Resource;
import fr.norsys.mapper.console.service.LdapTreeBuilder;

public class MandatoryAttributesTag extends BodyTagSupport {
	private static final long serialVersionUID = 1550050540337404252L;

public int doStartTag() throws JspException {
		try {
			Application currentAppli = (Application) pageContext.getSession()
					.getAttribute(ConsoleCst.CURRENT_APPLICATION);
			Resource currentRes = (Resource) pageContext.getSession()
					.getAttribute(ConsoleCst.CURRENT_RESOURCE);
			if (currentAppli != null && currentRes != null) {
				if (currentRes.getBaseDn() != null) {
					ApplicationContext ctx = WebApplicationContextUtils
							.getWebApplicationContext(pageContext
									.getServletContext());
					LdapTreeBuilder ldapTreeBuilder = (LdapTreeBuilder) ctx
							.getBean("ldapTreeBuilder");
					ldapTreeBuilder.setConnection(currentAppli.getConnection());
					Set s = ldapTreeBuilder.getMandatoryAttributes(currentRes
							.getBaseDn());
					if (s == null) {
						for (Iterator it2 = currentRes.getAttributes()
								.iterator(); it2.hasNext();) {
							Attribute a = (Attribute) it2.next();
							a.setMandatory(ConsoleCst.UNKNOWN_STATUS);
						}
					} else {
						if(ConsoleCst.ADD_MAPPER_TYPE.equals(currentRes.getType())) {
							for (Iterator it2 = currentRes.getAttributes()
									.iterator(); it2.hasNext();) {
								Attribute a = (Attribute) it2.next();
								a
										.setMandatory(s.contains(a
												.getAttributeLDAP()) ? ConsoleCst.MANDATORY_STATUS
												: ConsoleCst.NOT_MANDATORY_STATUS);
							}
						} else {
							for (Iterator it2 = currentRes.getAttributes()
									.iterator(); it2.hasNext();) {
								Attribute a = (Attribute) it2.next();
								a
										.setMandatory(ConsoleCst.NOT_MANDATORY_STATUS);
							}
						}
					}
				} else {
					for (Iterator it2 = currentRes.getAttributes().iterator(); it2
							.hasNext();) {
						Attribute a = (Attribute) it2.next();
						a.setMandatory(ConsoleCst.UNKNOWN_STATUS);
					}
				}
			}
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
		return EVAL_BODY_BUFFERED;
	}	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	} // doEndTag

	public void release() {
	}// release
}
